package com.xinyue.game.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.xinyue.game.server.codec.GameMessage;
import com.xinyue.game.server.codec.message.IGameMessage;
import com.xinyue.game.server.common.GameServerUtil;
import com.xinyue.game.server.dispatcher.GameMessageDispatcher;
import com.xinyue.game.server.dispatcher.GameServerContext;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class GameLogicHandler extends ChannelInboundHandlerAdapter {
	private ApplicationContext appContext;
	private Logger logger = LoggerFactory.getLogger(GameLogicHandler.class);
	private GameMessageDispatcher gameMessageDispatcher;

	public GameLogicHandler(ApplicationContext appContext) {
		this.appContext = appContext;
		gameMessageDispatcher = appContext.getBean(GameMessageDispatcher.class);
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("客户端：{} 连接成功,channelId:{}", GameServerUtil.getRemoteIP(ctx.channel()),
				ctx.channel().id().asShortText());
	}
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.debug("客户端:{}断开，channelId:{}", GameServerUtil.getRemoteIP(ctx.channel()),
				ctx.channel().id().asShortText());
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		GameMessage gameMessage = (GameMessage) msg;
		int messageId = gameMessage.getHeader().getMessageId();
		IGameMessage request = gameMessageDispatcher.getGameMessageRequestInstance(messageId);
		request.setHeader(gameMessage.getHeader());
		request.readBody(gameMessage.getBody());
		GameServerContext stx = new GameServerContext(ctx, request.getHeader());
		gameMessageDispatcher.callMethod(request, stx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.error("服务器内部异常", cause);
	}
}
